R Markdown

Allows you to create documents such as Word, html, pdf and PowerPoint directly from R incorporating outputs and code directly into the document.

Creating an R Markdown document

File -> New File… -> R Markdown..

Note: You can change between file types at a later time.

RStudio will have created a template. Consisting of a YAML and examples.

-–
title: “RMarkdown Tutorial”
author: “Tom Dougall”
date: “08/11/2021”
output: html_document
-–

To create your output file, click ‘Knit’ at the top of the script.

Basic formatting

Headers

#’s before text will indicate it is a header, the more #s, the smaller the header

# Header 1

## Header 2

### Header 3

  • End a line with two spaces to create a new paragraph
  • *italtics* for italics OR _italics_
  • **bold** for bold OR __bold__
  • ~~strikethrough~~ for strikethrough
  • * or - or + for a bullet point
    • indent a bulletpoint by four spaces to make nest it
  • Write code formatted text by using two back ticks `code`

Code Chunks

Chunks of code and their output can be included in an RMarkdown file. They are written with the following syntax;

```{r }
R code here.
```

Within the chunk header, we can set several options such as;

  • {r, include = FALSE} prevents code and results from appearing in the finished file. R Markdown still runs the code in the chunk, and the results can be used by other chunks.
  • {r, echo = FALSE} prevents code, but not the results from appearing in the finished file. This is a useful way to embed figures.
  • {r, message = FALSE} prevents messages that are generated by code from appearing in the finished file.
  • {r, warning = FALSE} prevents warnings that are generated by code from appearing in the finished.

Creating an RMarkdown in RStudio will by default set a global options, these can be overwritten in any chunk. The default is to show all code in output

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

RStudio have a handy cheat sheet for text formatting and code chunks options. https://www.rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf

Exercise 1: Create an RMarkdown file, and using data(iris), do the following

  • Create an RMarkdown file to output to html
  • Set the default options to not show any code in your markdown
  • Format the following with appropriate formatting.
    • The bold fox went to visit the tower of Pisa but found it too leaning.
  • Using the iris dataset, plot petal length vs petal width, make sure your code is visible with the output
  • Ensure your paragraph and plot have formatted headers

Using Chunks and its options

Best practice is to name all your chunks, it will help you troubleshoot by tracking which chunks has broken. When naming your chunk, it must be given a unique name, if you don’t assign a name, R will assign a default name with an incremental number. When writing your chunk header, it must be on a single line.

```{r cars-plot, include=TRUE}
data(mtcars)
plot(cars$speed, cars$dist)
```

Beyond the options we’ve seen so far, there are a lot more we can use. We can improve out plot by adding a label cars-plot and a title in the header {r label=cars-plot, fig.cap = "A plot showing the stopping disance of cars by the speed they were travelling"}. The title will append a figure caption to the plot.

A plot showing the stopping disance of cars by the speed they were travelling

A plot showing the stopping disance of cars by the speed they were travelling

We can also set other plot options such as

  • fig.width
  • fig.height
  • fig.align

Beyond plots we can also include options that impact areas such as;

  • Code evaluation
  • Text outputs
  • Animations

Possible options are linked here: https://yihui.org/knitr/options/

In line Code

You can also include outputs from code within your text. r max(cars$speed) which will output within the text (requires single closing quotation marks).

The max car speed tested is 25 from the cars dataset.

Exercise 2

  • Use in-line code to automate the report date to the current date. (Note: it will still require quotation marks around your inline code)
  • The fox actually visited Pisa 65 days ago, calculate when they went and insert it into your text.
  • Update your plot to give it a caption of what it shows, and set the width to 10 and height to 5

YAML Headers

RStudio will give you a default YAML header but there are a lot of options not given by default.

title: "Exercise 1 Answers"  
author: "Tom Dougall"  
date: "09/11/2021"  
output: html_document  

The output determines what type of document you want to create, this was auto-generated when creating the R script in RStudio. Within RStudio we can change the document we wish to write by clicking the arrow next to knit and choosing an option such as ‘Knit to word’. In doing so, the YAML will automatically update.

output: html_document

to

output: 
  word_document: default
  html_document: default

In the future when we knit - two documents will be created, a word and html version.

Some other option examples include;

  • subtitle - will add a smaller title to your document
  • code_folding - will enable the reader to hide code
  • code_folding: show - code will be visible by default
  • code_folding: hide - code will be hidden by default

Some options affect the styling of the document so need to be contained within the output setting.

output: 
  html_document:     
    * `toc: true` - will add a contents page  
    * `number_sections: true` - will number your contents page  

Themes: You can apply themes to your document, some are already included such as ‘cerulean’ and others have been developed within packages such as the ones found here: https://www.datadreaming.org/post/r-markdown-theme-gallery/. Alternatively you can use previously made documents to apply themes to your outputs.

In-built themes
 output:  
  html_document:
    theme: "default", "bootstrap", "cerulean", "cosmo", "darkly", "flatly", "journal", "lumen", "paper", "readable", "sandstone", "simplex", "spacelab", "united", "yeti"
Custom developed themes
output: rmdformats::readthedown
Themes from template document
 output:  
  word_document:   
    reference_docx: word_template.docx  

Exercise 3

  • Set your global options so that code is shown by default
  • Update your YAML to include a contents page and include code folding starting with it hidden
  • Pick a theme for your document, using the ‘cerulean’ in-built theme
  • Knit your document as a word document without editing the YAML
  • Some features are dependent on your document type, try knitting as a html document after

Tables

By default, RMarkdown will display output from your chunks as they’d appear in your console. Tables can rendered using your template’s style or with additional formatting by using the knitr::kable function.

knitr::kable(head(cars))
speed dist
4 2
4 10
7 4
7 22
8 16
9 10

Interactive Elements

html documents allow you to insert interactive elements, such as tables and plots. If you are familiar with RShiny then you may have come across them before.

Tables

The ‘DT’ package will give you filterable and sortable tables.

library(DT)
datatable(cars)

plotly

The ‘plotly’ package will give you plots with features such as zooming in, or hovering over points.

library(plotly) 
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(ggplot2)
plotExample <- ggplot( cars, aes(x=speed, y= dist)) +
geom_point()
ggplotly(plotExample)